//
//  ActiveEditVCViewController.swift
//  MoodDiary
//
//  Created by TanJian on 2021/12/18.
//

import UIKit
import Charts
import SVProgressHUD


private let reuseIdentifier = "ActiveEditCollectionViewCell"
private let cellSpacing: CGFloat = 5
private let cellWH: CGFloat = floor((UIScreen.main.bounds.width - 5*2 - 15*2) / 3)

class ActiveEditVCViewController: UIViewController,UICollectionViewDragDelegate, UICollectionViewDropDelegate,UICollectionViewDelegate,UICollectionViewDataSource,ActiveEditCollectionViewCellDelegate,ActiveAddViewControllerDelegate {
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    var imgDatesArr:[[String:Any]] = AppConstant.activeDatasArr
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.configImagesNames()

        
        // layout
        let layout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: cellSpacing, left: cellSpacing, bottom: cellSpacing, right: cellSpacing)
        layout.minimumLineSpacing = 25
        layout.minimumInteritemSpacing = cellSpacing
        layout.itemSize = CGSize(width: cellWH, height: cellWH+38)
        let bottom = getNotchBottomSafeArea() + 25.0
        layout.sectionInset = UIEdgeInsets(top: 0, left: 15, bottom: bottom, right: 15)
        layout.headerReferenceSize = CGSize(width: view.frame.width, height: 66.0)
        collectionView.setCollectionViewLayout(layout, animated: false)
        
        collectionView.register(UINib(nibName: reuseIdentifier, bundle: .main), forCellWithReuseIdentifier: reuseIdentifier)
        collectionView.register(UINib(nibName: "ActiveEditViewHeaderView", bundle: .main), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "ActiveEditViewHeaderView")
        collectionView.register(UINib(nibName: "ActiveEditViewFooterView", bundle: .main), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "ActiveEditViewFooterView")
        
        // 开启拖放手势，设置代理。
        collectionView.dragInteractionEnabled = true
        collectionView.dragDelegate = self
        collectionView.dropDelegate = self
        collectionView.delegate = self
        collectionView.dataSource = self
        
       
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "添加", style: .plain, target: self, action: #selector(addAction))
             
    }
    
    func configImagesNames(){
        
        if var imgArray = UserDefaults.standard.array(forKey: KUSERActiveImagesArrName ) as? [[String:Any]] {
            
            if let deletedImgArray = UserDefaults.standard.array(forKey: KUSERActiveDeletedImagesArrName) as? [[String:Any]] {
                imgArray.append(contentsOf: deletedImgArray)
            }
            imgDatesArr = imgArray
        }else{
            
            UserDefaults.standard.setValue(imgDatesArr, forKey: KUSERActiveImagesArrName)
            UserDefaults.standard.synchronize()
        }

    }
    
    @objc func addAction() {
        
        print("添加")
        let vc = ActiveAddViewController()
        vc.title = "活动编辑"
        vc.ActiveAddDelegate = self
        navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func tapAction(){
        
        
    }
    
    // MARK: ActiveAddViewControllerDelegate
    func refreshUI() {
        
        self.configImagesNames()
        
        collectionView.reloadData()
    }
    
    // MARK: ActiveEditCollectionViewCellDelegate
    func deleteCellAtIndexPath(indexPath: IndexPath) {
        
        
        if var deletedImgArray = UserDefaults.standard.array(forKey: KUSERActiveDeletedImagesArrName) as? [[String:Any]] {
            
            deletedImgArray.append(imgDatesArr[indexPath.item])
            UserDefaults.standard.setValue(deletedImgArray, forKey: KUSERActiveDeletedImagesArrName)
            
        }else{
            
            var tempDeletedImgArray = [[String:Any]]()
            tempDeletedImgArray.append(imgDatesArr[indexPath.item])
            UserDefaults.standard.setValue(tempDeletedImgArray, forKey: KUSERActiveDeletedImagesArrName)
        }
        
        imgDatesArr.remove(at: indexPath.item)

        
        UserDefaults.standard.setValue(imgDatesArr, forKey: KUSERActiveImagesArrName)
        UserDefaults.standard.synchronize()
        
        collectionView.reloadData()
    }

    
    // MARK: UICollectionViewDataSource, UICollectionViewDelegate
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imgDatesArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cellData = imgDatesArr[indexPath.item]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ActiveEditCollectionViewCell
        
        if let isCustom = cellData["isCustom"] as? Bool{
            print("############")
            cell.deleteBtn.isHidden = !isCustom
            cell.indexPath = indexPath
            cell.ActiveDelegate = self
        }else{
            print("************")

        }
        
        cell.infoLabel.text = cellData["text"] as? String
        cell.imgView.image = UIImage.init(named: cellData["imgName"] as! String)

        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let cellData = imgDatesArr[indexPath.item]
        
        if let isCustom = cellData["isCustom"] as? Bool{
            
            if isCustom{
                
                let vc = ActiveAddViewController()
                vc.title = "活动编辑"
                vc.ActiveAddDelegate = self
                vc.customDict = cellData
                vc.customIndex = indexPath.item
                navigationController?.pushViewController(vc, animated: true)
            }else{
                SVProgressHUD.showInfo(withStatus: "暂不支持修改内置活动")
                SVProgressHUD.dismiss(withDelay: 1.0)
            }
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let headrView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "ActiveEditViewHeaderView", for: indexPath)
            return headrView
        }else {
            
            let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "ActiveEditViewFooterView", for: indexPath)
            return footerView

        }
    
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.width, height: 66.0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        
        return CGSize(width: collectionView.width, height: 0.1)
    }
    
    // MARK: -  UICollectionViewDragDelegate, UICollectionViewDropDelegate
    
    //开始拖拽
    func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
        
        let cellData = imgDatesArr[indexPath.item] as [String:Any]
        let text = cellData["text"]
        
        let itemProvider = NSItemProvider(object: text as! NSItemProviderWriting)
        let dragItem = UIDragItem(itemProvider: itemProvider) // <-- ERROR HERE, Even If i force cast as NSItemProviderWriting
        dragItem.localObject = cellData

        return [dragItem]

    }
    
    /// 设置拖拽cell的临时样式
    func collectionView(_ collectionView: UICollectionView, dragPreviewParametersForItemAt indexPath: IndexPath) -> UIDragPreviewParameters? {
        
        
        guard let cell = collectionView.cellForItem(at: indexPath) as? ActiveEditCollectionViewCell else { return nil }
        cell.deleteBtn.isHidden = true
        let previewParameters = UIDragPreviewParameters()
        previewParameters.visiblePath = UIBezierPath(roundedRect: cell.bounds, cornerRadius: 12)
        
        return previewParameters
    }
    
    func collectionView(_ collectionView: UICollectionView, dragSessionDidEnd session: UIDragSession) {
        print("结束拖拽&&&&&&&&&&&")
        collectionView.reloadData()
    }
    
    //是否接收拖拽内容
    func collectionView(_ collectionView: UICollectionView, canHandle session: UIDropSession) -> Bool {
        
        return session.canLoadObjects(ofClass: String.self)
    }

    // 拖动过程中不断反馈item位置。
    func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {
        
        return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
    }
    
    
    
    func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {
        
        let destinationIndexPath = coordinator.destinationIndexPath ?? IndexPath(item: 0, section: 0)
        
        for item in coordinator.items {
            
            if let sourceIndexPath = item.sourceIndexPath,
               let cellData = item.dragItem.localObject as? [String:Any] {
                
                collectionView.performBatchUpdates({
                    
                    imgDatesArr.remove(at: sourceIndexPath.item)
                    imgDatesArr.insert(cellData, at: destinationIndexPath.item)
                    collectionView.deleteItems(at: [sourceIndexPath])
                    collectionView.insertItems(at: [destinationIndexPath])
                    
                    UserDefaults.standard.setValue(imgDatesArr, forKey: KUSERActiveImagesArrName)
                    UserDefaults.standard.synchronize()
                })
                coordinator.drop(item.dragItem, toItemAt: destinationIndexPath)
            }
        }
    }
    
}

extension UIViewController {
    
    /// 底部安全区域
    public func getNotchBottomSafeArea() ->CGFloat{
        if #available(iOS 11, *) {
            guard let w = UIApplication.shared.delegate?.window, let unwrapedWindow = w else {
                return 0
            }
            return unwrapedWindow.safeAreaInsets.bottom
        }
        return 0
    }
}
